package com.ys.peony.ui.widget;

import android.content.Context;
import android.graphics.ColorMatrixColorFilter;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.ys.peony.utils.PixelUtils;

/**
 * Created by 59153 on 2017/9/20.
 */

public class MyImageView extends ImageView {
    private final static int LEN = 5;
    private int lastX;
    private int lastY;
    public MyImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        this.setOnTouchListener(null);
    }

    public final OnTouchListener VIEW_TOUCH_DARK = new OnTouchListener() {
        //变暗(三个-50，值越大则效果越深)
        public final float[] BT_SELECTED_DARK = new float[]{1, 0, 0, 0, -50, 0, 1,
                0, 0, -50, 0, 0, 1, 0, -50, 0, 0, 0, 1, 0};

        //变亮
        public final float[] BT_SELECTED_LIGHT = new float[]{1, 0, 0, 0, 50, 0, 1,
                0, 0, 50, 0, 0, 1, 0, 50, 0, 0, 0, 1, 0};
        //恢复
        public final float[] BT_NOT_SELECTED = new float[]{1, 0, 0, 0, 0, 0,
                1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0};

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int x = (int) event.getX();
            int y = (int) event.getY();
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    performClick();
                    lastX = x;
                    lastY = y;
                    ((ImageView) v).setColorFilter(new ColorMatrixColorFilter(BT_SELECTED_DARK));
                    break;
                case MotionEvent.ACTION_MOVE:
                    final int dealtX = x - lastX;
                    final int dealtY = y - lastY;
                    if (Math.abs(dealtX) >= PixelUtils.dp2px(LEN) || Math.abs(dealtY) >= PixelUtils.dp2px(LEN)) {
                        ((ImageView) v).setColorFilter(new ColorMatrixColorFilter(BT_NOT_SELECTED));
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    ((ImageView) v).setColorFilter(new ColorMatrixColorFilter(BT_NOT_SELECTED));
            }
            return true; //如为false，执行ACTION_DOWN后不再往下执行
        }
    };

    public void setTouchable(Boolean touchable) {
        if(touchable) {
            this.setOnTouchListener(VIEW_TOUCH_DARK);
        } else {
            this.setOnTouchListener(null);
        }
    }
}
